﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using Technewlogic.FileXChange.Common;

namespace Technewlogic.FileXChange
{
	public class FileUploadHelper
	{
		public FileUploadHelper(HttpRequest request)
		{
			_request = request;
		}

		private readonly HttpRequest _request;

		public string UploadPath
		{
			get
			{
				string path = Properties.Settings.Default.UploadPath;
				if (!Directory.Exists(path))
					Directory.CreateDirectory(path);

				path = new DirectoryInfo(path).FullName;
				return path;
			}
		}

		public bool TrySaveFileFromRequest()
		{
			if (_request.Files.Count > 0 && !string.IsNullOrEmpty(_request.Files[0].FileName))
			{
				string fileName = _request.Files[0].FileName;
				if (fileName.Contains(@"\"))
					fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1);

				using (FileStream fs = new FileStream(UploadPath + "\\" + fileName,
					FileMode.Create, FileAccess.Write, FileShare.None))
				{
					byte[] buffer = new byte[_request.Files[0].InputStream.Length];
					_request.Files[0].InputStream.Read(buffer, 0, buffer.Length);
					fs.Write(buffer, 0, buffer.Length);
					fs.Close();
				}

				return true;
			}
			else
				return false;
		}

		public void DeleteFile()
		{
			string fileName = _request.QueryString[Constants.QueryStringFilename];
			fileName = UploadPath + "\\" + fileName;
			if (!File.Exists(fileName))
				throw new FileNotFoundException("The file '" + fileName + "' does not exist.");

			File.Delete(fileName);
		}
	}
}
